package com.tydic.trans.service.impl;

import com.tydic.trans.beans.Account;
import com.tydic.trans.beans.Stock;
import com.tydic.trans.exceptions.StockException;
import com.tydic.trans.mapper.AccountMapper;
import com.tydic.trans.mapper.StockMapper;
import com.tydic.trans.service.StockService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StockServiceImpl implements StockService {

    //引用类型
    private AccountMapper adao;
    private StockMapper sdao;

    public void setAdao(AccountMapper adao) {
        this.adao = adao;
    }

    public void setSdao(StockMapper sdao) {
        this.sdao = sdao;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
    public int openAccount(Account account) {
        return adao.insertAccount(account);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.SUPPORTS, readOnly = true)
    public Account findAccount(String aname) {
        return adao.selectAccount(aname);
    }

    @Override
    //使用@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)相同的内容(默认)
    @Transactional
    public int openStock(Stock stock) {
        return sdao.insertStock(stock);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Stock findStock(String sname) {
        return sdao.selectStock(sname);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, timeout = 10, rollbackFor = StockException.class)
    public void buyStock(String aname, double money, String sname, int amount) throws StockException {
        //先从account扣钱
        Account account = new Account();
        account.setAname(aname);
        account.setBalance(money);
        adao.updateAccount(account);

        //抛出一个异常（如果账户余额小于要用于买股票的钱）
        //假如一个股票单价是2元
        //money = amount * 2;
        if (money < amount * 2) {
            throw new StockException("资金不足！！！");
        }

        //增加股票的数量， 修改stock表
        Stock stock = new Stock();
        stock.setSname(sname);
        stock.setCount(amount);
        sdao.updateStock(stock);
    }


}
